package cookie

import (
	"net/http"
)

type Option func(propagator *Propagator)

type Propagator struct {
	cookieName   string
	cookieOption func(cookie *http.Cookie)
}

func NewPropagator() *Propagator {
	return &Propagator{
		cookieName: "cookiename",
		cookieOption: func(cookie *http.Cookie) {

		},
	}
}

func WithCookieName(cookieName string) Option {
	return func(propagator *Propagator) {
		propagator.cookieName = cookieName
	}
}

func WithCookieOption(opt func(c *http.Cookie)) Option {
	return func(propagator *Propagator) {
		propagator.cookieOption = opt
	}
}

func (p *Propagator) Extra(req *http.Request) (string, error) {
	c, err := req.Cookie(p.cookieName)
	if err != nil {
		return "", err
	}
	return c.Value, nil
}

func (p *Propagator) Inject(id string, writer http.ResponseWriter) error {
	c := &http.Cookie{
		Name:  p.cookieName,
		Value: id,
	}
	p.cookieOption(c)
	http.SetCookie(writer, c)
	return nil
}

func (p *Propagator) Remove(writer http.ResponseWriter) error {
	// 设置cookie生命周期为-1
	c := &http.Cookie{
		Name:   p.cookieName,
		MaxAge: -1,
	}
	p.cookieOption(c)
	http.SetCookie(writer, c)
	return nil
}
